import React, { useCallback, useContext, useEffect, useMemo, useState } from 'react';

import { Popover, Tree, Spin, Empty } from 'antd';

import cls from 'classnames';

import ScrollBarLayout from '@/components/ScrollBarLayout';

import pageStyles from '@/common/pageLayout.less';

import { PlusCircleOutlined, EditOutlined, EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
import MyIcon from '@/components/MyIcon';
import { DictionaryTypeAdd } from './DictionaryTypeAdd';
import { DictionaryTypeEdit } from './DictionaryTypeEdit';
import { IDictionaryTypeTree } from '../type';
import { DictionaryContext } from '../hooks';

export const DictionaryTypeTree: React.FC<IDictionaryTypeTree> = ({ loading, reloadTree }) => {
  const {
    prefixCls,
    searchValue,
    treeData,
    selectKeys,
    expandedKeys,
    autoExpandParent,
    commonDispatch,
    reloadTableDataSource
  } = useContext(DictionaryContext);

  useEffect(() => {
    if (treeData && treeData?.length > 0) {
      onTreeSelect([treeData[0]?.id]);
    }
  }, [treeData]);

  const [showAppendType, setShowAppendType] = useState(false);

  const [showEditType, setShowEditType] = useState(false);

  const [record, setRecord] = useState({});

  const onOpenAppendType = () => {
    setShowAppendType(true);
  };

  const onCloseAppendType = () => {
    setShowAppendType(false);
  };

  const onOpenEditType = () => {
    setShowEditType(true);
  };

  const onCloseEditType = () => {
    setShowEditType(false);
  };

  const onTreeNodeMouseEnter = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'block';
    }
  };

  const onTreeNodeMouseLeave = (id: string, flag: boolean) => {
    const ele = document.getElementById(id);
    if (flag) {
      return;
    } else if (ele) {
      ele.style.display = 'none';
    }
  };

  const getTreeIcon = (flag: any) => {
    return (
      <a style={{ marginRight: 3 }}>
        {flag ? <MyIcon type={'icon-ic-normal-zidianguanli'} /> : <MyIcon type={'icon-icon-test2'} />}
      </a>
    );
  };

  /**
   * 是否显示 详情气泡
   */
  const [showPopoverID, setShowPopoverID] = useState<string>('');

  /**
   * 显示 隐藏 详情方法
   * @param openID  显示图标
   * @param closeID  闭合图标
   * @param showPopo  显示详情的 id
   * @param isOpen  true 显示     false 隐藏
   */
  const clickEyeDetail = (openID: string, closeID: string, showPopo: string, isOpen: boolean) => {
    const eleOpen = document.getElementById(openID);
    const eleClose = document.getElementById(closeID);
    if (eleOpen) {
      eleOpen.style.display = isOpen ? 'none' : 'inline-block';
    }
    if (eleClose) {
      eleClose.style.display = isOpen ? 'inline-block' : 'none';
    }
    setShowPopoverID(showPopo);
  };

  const loopTreeData = (data: Record<string, any>[]): Record<string, any>[] => {
    return data?.map((item) => {
      //const idName = Math.random() * 1000 + '-' + item?.id;
      const idName = item?.id;

      const detailEyeShow = item?.id + 'eyeShow' + Math.random();

      const detailEyeHiddren = item?.id + 'eyeHiddren' + Math.random();

      const showpopoverDom = item?.id + 'showpopoverDom';

      // const flag = item?.id == selectKeys?.[0];
      const flag = false;

      const content = (
        <div style={{ color: '#000000D9' }}>
          <p>
            编号：
            {item?.id}
          </p>
          <p>
            名称：
            {item?.name}
          </p>
          <p>
            科目：
            {item.setSubject == 0 ? <span>未设置</span> : <span>设为科目</span>}
          </p>
          <p>
            流程：
            {item.setFlow == 0 ? <span>未设置</span> : item.setFlow == 1 ? <span>流程类别</span> : <span>流程状态</span>}
          </p>
          <p>
            状态：
            {item.isOpen == 0 ? <span style={{ color: 'red' }}>禁用</span> : <span style={{ color: 'green' }}>启用</span>}
          </p>
          <p>
            排序：
            {item?.seq}
          </p>
        </div>
      );
      const name = item?.name;
      const index = name?.indexOf(searchValue);
      const beforeStr = name?.substring(0, index);
      const afterStr = name?.slice(index + searchValue.length);

      const titleTree =
        index > -1 ? (
          <span className={pageStyles['over-flow-hidden']}>
            {beforeStr}
            <span style={{ color: '#f50' }}>{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );
      return {
        ...item,
        key: item?.id,
        title: (
          <Popover
            placement="bottomLeft"
            content={content}
            trigger={'click'}
            title={item.name}
            color={'rgb(222 222 222)'}
            destroyTooltipOnHide={{ keepParent: false }}
            overlayClassName={cls('dic-popover')}
            open={showpopoverDom == showPopoverID ? true : false}
          >
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
              }}
              id={item?.id + 'DesignLeftTreeType'}
              onMouseEnter={() => {
                onTreeNodeMouseEnter(idName, flag);
              }}
              onMouseLeave={() => {
                onTreeNodeMouseLeave(idName, flag);
                clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
              }}
            >
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                {getTreeIcon(item?.pID)}
                {titleTree}
              </div>
              <div
                id={idName}
                style={{
                  whiteSpace: 'nowrap',
                  display: flag ? 'block' : 'none',
                }}
              >
                <a
                  style={{
                    display: 'inline-block',
                    marginRight: 8,
                  }}
                  id={detailEyeShow}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, showpopoverDom, true);
                  }}
                >
                  <EyeOutlined />
                </a>
                <a
                  id={detailEyeHiddren}
                  style={{
                    display: 'none',
                    marginRight: 8,
                  }}
                  onClick={(e) => {
                    e?.stopPropagation();
                    clickEyeDetail(detailEyeShow, detailEyeHiddren, '', false);
                  }}
                >
                  <EyeInvisibleOutlined />
                </a>
                <a
                  style={{ marginRight: 8 }}
                  onClick={(e) => {
                    if (e && e.stopPropagation) {
                      e.stopPropagation();
                    }
                    onAppendDicType(item?.id);
                  }}
                >
                  <PlusCircleOutlined />
                </a>
                <a
                  onClick={(e) => {
                    if (e && e.stopPropagation) {
                      e.stopPropagation();
                    }
                    onEditDicType(item);
                  }}
                >
                  <EditOutlined />
                </a>
              </div>
            </div>
          </Popover>
        ),
        children: item?.children ? loopTreeData(item?.children) : null,
      };
    });
  };

  const typeTreeData = useMemo(() => {
    return loopTreeData(treeData);
  }, [treeData, searchValue, showPopoverID]);

  const onTreeSelect = (value: any) => {
    commonDispatch({
      type: 'edit-selectKeys',
      payload: value,
    });
    if (value && value?.length > 0) {
      const [id] = value;
      reloadTableDataSource(id);
    } else {
      commonDispatch({
        type: 'edit-selectKeys',
        payload: selectKeys,
      });
    }
  };

  const onTreeExpand = useCallback(
    (e: any) => {
      commonDispatch({
        type: 'edit-expandedKeys',
        payload: e,
      });
      commonDispatch({
        type: 'edit-autoExpandParent',
        payload: false,
      });
    },
    [expandedKeys],
  );

  const onAppendDicType = (key: string) => {
    const promise = new Promise((resolve, reject) => {
      onTreeSelect([key]);
      resolve(true);
    });

    promise.then((res) => {
      if (res) {
        onOpenAppendType();
      }
    });
  };

  const onEditDicType = (record: Record<string, any>) => {
    const promise = new Promise((resolve, reject) => {
      onTreeSelect([record?.id]);
      setRecord(record);
      resolve(true);
    });

    promise.then((res) => {
      if (res) {
        onOpenEditType();
      }
    });
  };

  return (
    <>
      <div className={cls(prefixCls + 'tree-child')}>
        <ScrollBarLayout style={{ padding: '0rem 1rem 0.5rem' }}>
          <Spin
            spinning={loading}
            style={{
              width: '100%',
              marginTop: 24,
            }}
          >
            {treeData && treeData?.length > 0 ? (
              <Tree
                treeData={typeTreeData}
                blockNode={true}
                selectedKeys={selectKeys}
                onSelect={onTreeSelect}
                expandedKeys={expandedKeys}
                onExpand={onTreeExpand}
                autoExpandParent={autoExpandParent}
              />
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </Spin>
        </ScrollBarLayout>
      </div>

      {showAppendType && <DictionaryTypeAdd onClose={onCloseAppendType} reloadTree={reloadTree} />}
      {showEditType && <DictionaryTypeEdit onClose={onCloseEditType} reloadTree={reloadTree} record={record} />}
    </>
  );
};
